package com.haifeng.jupiter.auth.impl;

import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import com.haifeng.jupiter.common.core.base.Rest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>
 *  需要认证登录的处理器
 * </p>
 *
 * @author: Haifeng
 * @date: 2020-08-22
 */
@Slf4j
public class LoginEntryPoint implements AuthenticationEntryPoint {

    /**
     * 业务描述：前后的分离不用跳转login页面，直接返回401
     *
     * @param request
     * @param response
     * @param authException
     * @return
     */
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        Rest rest = Rest.error(HttpStatus.HTTP_UNAUTHORIZED, "请先登录");
        response.getWriter().write(JSONUtil.parseObj(rest, false).toString());
    }
}
